package ua.com.minus1.lookbattle;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import ua.com.devsmart.android.ui.HorizontalListView;

/**
 * Created with IntelliJ IDEA.
 * User: Igorek
 * Date: 8/25/12
 * Time: 9:37 PM
 * To change this template use File | Settings | File Templates.
 */
public class CatsList extends FrameLayout{

    private OnItemClickListener itemClickListener;
    private AdapterView adapterView;

    public CatsList(Context context) {
        super(context);
        setupView();
    }

    public CatsList(Context context, AttributeSet attrs) {
        super(context, attrs);
        setupView();
    }

    public void setOnItemClickListener(OnItemClickListener itemClickListener) {

        this.itemClickListener = itemClickListener;
    }

    private void setupView() {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        adapterView = (AdapterView) inflater.inflate(R.layout.cats_list, null);
        adapterView.setAdapter(new CatsAdapter(CatItemFactory.createItems(getContext())));
        adapterView.setOnItemClickListener(new CatItemClickListener());
        addView(adapterView);
    }

    private class CatsAdapter extends ArrayAdapter<CatItemFactory.CatItem> {
        private CatsAdapter(CatItemFactory.CatItem[] catItems) {
            super(CatsList.this.getContext(), 0, catItems);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = new ImageView(getContext());
                convertView.setLayoutParams(new ListView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            }
            CatItemFactory.CatItem catItem = getItem(position);

            ((ImageView) convertView).setImageDrawable(catItem.icon);

            return convertView;
        }
    }

    private class CatItemClickListener implements AdapterView.OnItemClickListener {
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if (itemClickListener != null) {
                CatItemFactory.CatItem catItem = ((CatsAdapter) adapterView.getAdapter()).getItem(i);
                itemClickListener.onItemClick(catItem);
            }

        }
    }

    public interface OnItemClickListener{
        void onItemClick(CatItemFactory.CatItem catItem);
    }
}
